<?php
/*
 * Created on 2009-3-25
 *
 * Class for pagination
 * created by Joe Qiao [mynamesucks@163.com]
 * You can copy this file to wherever you want, but you must remain the author info
 */

class Pagination {
	public $paginationString;
	public $begin;
	public $end;
	public $pageNum;
	private $totalNum;	
	private $pageRecordNum;
	private $pageDelta;	
	
	public function __construct($totalNum, $pageRecordNum, $pageNum, $pageDelta) {
		$this->paginationString = '';
		$this->totalNum = $totalNum;
		$this->pageRecordNum = $pageRecordNum;
		$this->pageNum = $pageNum;
		if(!isset($this->pageNum)) {
			$this->pageNum = 1;
		}
		$this->pageDelta = $pageDelta;
		$this->calculateLimit();
		$this->generatePagination();
	}
	
	private function calculateLimit() {
		if(1 === (int)$this->pageNum) {
			$this->begin = 0;
		}
		else {
			$this->begin = ($this->pageNum - 1) * $this->pageRecordNum;			
		}
		$this->end = $this->pageRecordNum;
	}
	
	private function generatePagination() {
		$lastPage = ceil($this->totalNum / $this->pageRecordNum);
		
		//remove the page param from $_SERVER['REQUEST_URI']
		$requestUri = preg_replace("/\?page=[0-9]*/i", "", $_SERVER['REQUEST_URI']);
		$requestUri = preg_replace("/\&page=[0-9]*/i", "", $requestUri);
		
		if(stripos($requestUri, "?")) {
			$pageSeparator = '&';
		}
		else {
			$pageSeparator = '?';
		}
		
		if($this->pageNum > 1) {
			$this->paginationString .= '<a href="'.$requestUri.$pageSeparator.'page=1" class="gray_12px">'.FIRST_PAGE.'</a> | <a href="'.$requestUri.$pageSeparator.'page='.($this->pageNum - 1).'" class="gray_12px">'.PREVIOUS_PAGE.'</a> | ';
		}
		$prefix = $this->pageNum - $this->pageDelta;
		$suffix = $this->pageNum + $this->pageDelta;
		while($prefix < $this->pageNum) {
			if($prefix > 0) {
				$this->paginationString .= '<a href="'.$requestUri.$pageSeparator.'page='.$prefix.'" class="gray_12px">'.$prefix.'</a> ';
			}
			$prefix ++;
		}
		$this->paginationString .= ' '.$this->pageNum.' ';
		$tempPageNum = $this->pageNum + 1;
		while($tempPageNum <= $suffix) {
			if($tempPageNum <= $lastPage) {
				$this->paginationString .= '<a href="'.$requestUri.$pageSeparator.'page='.$tempPageNum.'" class="gray_12px">'.$tempPageNum.'</a> ';
			}
			$tempPageNum ++;
		}
		if($lastPage != $this->pageNum) {
			$this->paginationString .= ' | <a href="'.$requestUri.$pageSeparator.'page='.($this->pageNum + 1).'" class="gray_12px">'.NEXT_PAGE.'</a> | <a href="'.$requestUri.$pageSeparator.'page='.$lastPage.'" class="gray_12px">'.LAST_PAGE.'</a>';
		}
	}
}
?>
